package com.dong.springshell.service.impl;

import com.dong.springshell.service.TestService;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@RequiredArgsConstructor
@Service
public class TestServiceImpl implements TestService {

    private final JdbcTemplate jdbcTemplate;

    private final PlatformTransactionManager transactionManager;

    @Transactional
    @Override
    public void testJdbcTemplate() {

//        jdbcTemplate.batchUpdate("INSERT INTO t_order (order_number, order_data) VALUES ('code-003', '{}')");
//        jdbcTemplate.batchUpdate("INSERT INTO t_order (order_number, order_data) VALUES ('code-004', '{}')");

        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            jdbcTemplate.execute("ALTER TABLE t_order ADD one VARCHAR(50) DEFAULT NULL COMMENT '一个注释'");
            double x = 1 / 0;
            transactionManager.commit(status);
        } catch (Exception e) {
            // 在这里处理异常，比如打印日志
            transactionManager.rollback(status);
            throw e; // 可以选择重新抛出异常，或者处理它
        }
    }

}
